package spring.cloud.tasks.tasks_manager.tasks_manager.listener;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import spring.cloud.tasks.tasks_manager.tasks_manager.node.Node;
import spring.cloud.tasks.tasks_manager.tasks_manager.service.AllotTaskItemService;

@Slf4j
@Setter
@Getter
public class LeadershipElectionListener extends TreeCacheListener {

    private AllotTaskItemService allotTaskItemService;

    public LeadershipElectionListener(AllotTaskItemService allotTaskItemService) {
        this.allotTaskItemService = allotTaskItemService;
    }

    @Override
    public void childEvent(TreeCacheEvent.Type type, String path, String nodeData) throws Exception {
        if (isLeaderRemove(type, path)) {
            allotTaskItemService.leaderElection();
        }
    }

    private boolean isLeaderRemove(TreeCacheEvent.Type type, String path) {
        return type == TreeCacheEvent.Type.NODE_REMOVED && Node.LEADER_HOSTNODE_PATH.equals(path);
    }
}
